package group.ocr.Service.Impl;

import group.ocr.Service.ImageService;
import group.ocr.Service.OCRService;
import okhttp3.*;

import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

@Service
public class OCRServiceImpl implements OCRService {

    @Autowired
    private ImageService imageService;

    // API接入的 token 和 email
    public static final String token = "35a41b75-deea-4ee4-b06e-5b1a6c74a0b9";
    public static final String email = "1473763052@qq.com";
    private static final String OCR_API_URL = "https://ocr.kandianguji.com/ocr_api"; // 接口地址

    @Override
    public String imageRecognition(MultipartFile image) throws IOException, JSONException {
        // 将图片转换为Base64编码
        String base64Image = encodeImageToBase64(image);
        // 调用OCR API进行识别
        return callOCRAPI(token, email, base64Image);
    }

    // 图片转Base64编码
    private String encodeImageToBase64(MultipartFile image) throws IOException {
        byte[] bytes = image.getBytes();
        return Base64.getEncoder().encodeToString(bytes);
    }

    // 调用OCR API
    private String callOCRAPI(String token, String email, String base64Image) throws IOException, JSONException {
        // 构建请求参数
        JSONObject jsonPayload = new JSONObject();
        jsonPayload.put("token", token);
        jsonPayload.put("email", email);
        jsonPayload.put("image", base64Image); // Base64编码的图片内容
        jsonPayload.put("return_position",true);
        // 发送POST请求
        URL url = new URL(OCR_API_URL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        // 设置请求类型
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Accept", "application/json");
        // 写入请求参数
        try (OutputStream os = connection.getOutputStream()) {
            byte[] input = jsonPayload.toString().getBytes(StandardCharsets.UTF_8);
            os.write(input, 0, input.length);
        }

        // 获取响应内容
        int responseCode = connection.getResponseCode();
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        // 判断响应状态
        if (responseCode == HttpURLConnection.HTTP_OK) {
            return response.toString(); // 成功时返回OCR结果
        } else {
            throw new IOException("Failed to call OCR API: " + responseCode + " - " + response);
        }
    }
}
